import paho.mqtt.client as mqtt
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import os
import threading
import time
import telepot
from telepot.loop import MessageLoop

client = mqtt.Client()
current_message = ''
chrome_options = ''
driver = ''
url = 'NULL'

temp_radiator = ''
temp_boiler = ''
temp_room = ''
temp_storeroom = ''
hum_storeroom = ''
hum_room = ''

token = ''
TelegramBot = telepot.Bot(token)

def handle(msg):
    global current_message
    global temp_radiator
    global temp_boiler
    global temp_room
    global temp_storeroom
    global hum_storeroom
    global hum_room
    global url
    global driver

    content_type, chat_type, chat_id = telepot.glance(msg)

    command = msg['text'].lower();
    print ("COMMAND = "+command)

    print ("CHAT ID = "+str(chat_id))
    if str(chat_id) != '3072759':
        TelegramBot.sendMessage('3072759',"Неавторизованный доступ к боту!")
        TelegramBot.sendMessage('3072759',"Ввод команды: "+command)

    if 'https://www.youtube.com' in command and str(chat_id) == '3072759':
        print("YOUTUBE URL")
        url = command

    if command == '/camera' and str(chat_id) == '3072759':
        print("SEND PICTURES")
        os.system("bash /home/max/multimedia/camera.sh")

    if command == '/camera_home' and str(chat_id) == '3072759':
        print("SEND PICTURES")
        os.system("bash /home/max/multimedia/camera_home.sh")

    if command == '/camera_ext' and str(chat_id) == '3072759':
        print("SEND PICTURES")
        os.system("bash /home/max/multimedia/camera_ext.sh")

    if command == '/record' and str(chat_id) == '3072759':
        print("RECORD ON")
        os.system("bash /home/max/multimedia/arecord_tg.sh")

    if command == '/temperature' and str(chat_id) == '3072759':
        TelegramBot.sendMessage('3072759','Температуара: котла = '+temp_boiler+', радиатора = '+temp_radiator+', комнаты = '+temp_room+', кладовки = '+temp_storeroom+'. Влажность: кладовка = '+hum_storeroom+', комната = '+hum_room)

    if command == '/soundcheck' and str(chat_id) == '3072759':
        logs =[]
        i = 0
        with open("/home/max/multimedia/meter.log", "r") as file:
            lines = file.readlines()
            for line in lines[-30:]:
                words = line.split()
                logs.append(words[-1])
                i = i + int(words[-1])
        i = i / 30
        TelegramBot.sendMessage('3072759',logs)
        TelegramBot.sendMessage('3072759',i)

    if command == '/lofi' and str(chat_id) == '3072759':
        url = "https://www.youtube.com/watch?v=jfKfPfyJRdk"

    if command == '/yandex' and str(chat_id) == '3072759':
        url = "https://music.yandex.ru/home"

    if command == '/tv' and str(chat_id) == '3072759':
        url = 'https://vgtrk.ru/russia24'

    if command == '/up' and str(chat_id) == '3072759':
        os.system("/usr/bin/amixer -c 3 sset Speaker 5%+")

    if command == '/down' and str(chat_id) == '3072759':
        os.system("/usr/bin/amixer -c 3 sset Speaker 5%-")

    if command == '/stop':
        try:
            current_message = 'NULL'
            driver.close()
            driver.quit()
            os.system("killall chromium")
            os.system("killall chromedriver")
            os.system("killall chromium-browser")
        except:
            pass


def init_chrome(url):
    global chrome_options
    global driver
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument('--user-data-dir=/home/max/multimedia/chromium')
    #chrome_options.add_argument('--headless')
    chrome_options.add_experimental_option("detach", True)
    driver = webdriver.Chrome(chrome_options=chrome_options)
    print("LOADED URL: "+url)

    if 'vgtrk.ru/russia24' in url:
        os.system("/usr/bin/amixer -c 3 sset Speaker 100%")
        try:
            driver.get(url)
            time.sleep(10)
            print("SWITCH IFRAME")
            driver.switch_to.frame(0)
            print("CLICK BUTTON")
            driver.find_element(By.ID, "ya-mute").click()
        except:
            pass

    if "https://www.youtube.com" in url and 'jfKfPfyJRdk' not in url:
        os.system("/usr/bin/amixer -c 3 sset Speaker 50%")
        try:
            driver.get(url)
        except:
            pass


    if 'jfKfPfyJRdk' in url:
        os.system("/usr/bin/amixer -c 3 sset Speaker 50%")
        try:
            driver.get(url)
        except:
            pass

    if 'https://music.yandex.ru/home' in url:
        print("volume up!")
        os.system("/usr/bin/amixer -c 3 sset Speaker 80%")
        try:
            driver.get(url)
            WebDriverWait(driver, 30).until(expected_conditions.text_to_be_present_in_element((By.CSS_SELECTOR, ".rup__content-button-caption"), "Моя волна"))
            driver.find_element(By.CSS_SELECTOR, ".rup__content-button-play > .d-icon").click()
        except:
            pass
    pass

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("#")

def on_message(client, userdata, msg):
    global driver
    global url
    global current_message
    global temp_radiator
    global temp_boiler
    global temp_room
    global temp_storeroom
    global hum_storeroom
    global hum_room
    current_topic = msg.topic

    payload = str(msg.payload,'utf-8')
    print(current_topic + " = " +payload)

    if (current_topic == "wemos/temp"):
        current_message = msg.payload
        current_message = current_message.decode("utf-8")
        temp_boiler = current_message

    if (current_topic == "wemos/temp_radiator"):
        current_message = msg.payload
        current_message = current_message.decode("utf-8")
        temp_radiator = current_message

    if (current_topic == "wemos_room_2/temp"):
        current_message = msg.payload
        current_message = current_message.decode("utf-8")
        temp_storeroom = current_message

    if (current_topic == "wemos_room_2/humidity"):
        current_message = msg.payload
        current_message = current_message.decode("utf-8")
        hum_storeroom = current_message

    if (current_topic == "wemos_room/temp"):
        current_message = msg.payload
        current_message = current_message.decode("utf-8")
        temp_room = current_message

    if (current_topic == "wemos_room/humidity"):
        current_message = msg.payload
        current_message = current_message.decode("utf-8")
        hum_room = current_message

    if (current_topic == "pc/volume"):
        current_message = msg.payload
        current_message = current_message.decode("utf-8")
        os.system("/usr/bin/amixer -c 3 sset Speaker "+current_message+"%")

    if (current_topic == "pc/multimedia"):
        print ("NEEDED TOPIC")
        current_message = msg.payload
        current_message = current_message.decode("utf-8")

        print ("current_message = "+current_message)

        if (current_message == "youtube"):
            print ("start music from youtube")
            url = "https://www.youtube.com/watch?v=jfKfPfyJRdk"

        if (current_message == "tv"):
            print ("start TV")
            url = "https://vgtrk.ru/russia24"

        if (current_message == "yandex"):
            print ("start music from yandex")
            url = "https://music.yandex.ru/home"

        if current_message == 'record':
            print("RECORD ON")
            os.system("bash /home/max/multimedia/arecord_tg.sh")

        if current_message == 'camera':
            print("SEND PICTURES")
            os.system("bash /home/max/multimedia/camera.sh")

        if current_message == 'motion':
            print("SEND AREA")
            os.system("bash /home/max/multimedia/camera_motion.sh")

def watch():
    global driver
    global url
    global current_message

    while True:
        if (url != 'NULL'):
            try:
                print ("START BROWSER with URL = "+url)
                init_chrome(url)
                url = 'NULL'
            except:
                pass

        if (current_message == "stop"):
            try:
                current_message = 'NULL'
                driver.close()
                driver.quit()
                os.system("killall chromium")
                os.system("killall chromedriver")
                os.system("killall chromium-browser")
            except:
                pass

        print("check URL value...")
        time.sleep(2)
    pass

def mqttt():
    global client
    client.on_connect = on_connect
    client.on_message = on_message
    client.username_pw_set("", "")
    client.connect("", 1883, 60)
    client.loop_start()
    pass

MessageLoop(TelegramBot, handle).run_as_thread()

thread_watch = threading.Thread(target=watch, name="watch")
thread_mqttt = threading.Thread(target=mqttt, name="mqttt")

thread_watch.start()
thread_mqttt.start()

thread_watch.join()
thread_mqttt.join()

